package com.johnson.news.share;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.johnson.news.R;
import com.johnson.news.event_msg.ShareMsg;
import com.johnson.news.util.Constants;
import com.johnson.news.util.ImageUtils;
import com.johnson.news.util.Utils;
import com.johnson.news.wxapi.Util;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.youmbe.library.util.ALiImageUtils;
import com.youmbe.library.util.MyToast;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;

import androidx.annotation.Nullable;

public class ShareAppUtils {
    private static Context mContext;
    String mShareUrl, mShareTitle, mShareDesc, mShareImage;
    Bitmap shareBitmap;
    /* 微信相关 */
    private IWXAPI api;
    //    /* QQ相关 */
    public static Tencent TENCENT = null;
    /* 微博相关 */
//    public IWeiboShareAPI mWeiboShareAPI;

    WbShareHandler shareHandler;
    int supportApiLevel, mShareFlag;

    boolean hasShared = false;

    public ShareAppUtils(Context context, int shareFlag, String url, String title, String desc, String image) {
        mContext = context;
        mShareUrl = url;
        mShareTitle = title;
        mShareDesc = desc;
        mShareImage = image;
        mShareFlag = shareFlag;
        //
        if (TextUtils.isEmpty(mShareImage)) {
            Glide.with(mContext).asBitmap().load(R.mipmap.logo).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    shareBitmap = resource;
                    if (shareBitmap.isRecycled()) {
                        Log.e("recycle", "recycle");
                    }
                    switch (mShareFlag) {
                        case 1: // qq
                            shareToQQ();
                            break;
                        case 2: // 微信
                            shareToWeiXin();
                            break;
                        case 3: // 朋友圈
                            shareToMoment();
                            break;
                        case 4: // 微博
                            shareToSina();
                            break;
                    }
                }
            });
        } else {
            String iconUrl = ALiImageUtils.compressImageBySize(mShareImage, 100, 100);//图片太大调不起微信分享，用阿里云剪裁工具剪裁大小
            Glide.with(mContext).asBitmap().load(iconUrl).into(new SimpleTarget<Bitmap>() {//.apply(new RequestOptions().override(100))
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    shareBitmap = resource;
                    if (shareBitmap.isRecycled()) {
                        Log.e("recycle", "recycle");
                    }
                    switch (mShareFlag) {
                        case 1: // qq
                            shareToQQ();
                            break;
                        case 2: // 微信
                            shareToWeiXin();
                            break;
                        case 3: // 朋友圈
                            shareToMoment();
                            break;
                        case 4: // 微博
                            shareToSina();
                            break;
                    }
                }

                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                    if (!hasShared) {//图片加载失败后改用logo，取消分享时会自动调用此方法数次，故加此条件限制
                        hasShared = true;
                        shareBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.logo);
                        switch (mShareFlag) {
                            case 1: // qq
                                shareToQQ();
                                break;
                            case 2: // 微信
                                shareToWeiXin();
                                break;
                            case 3: // 朋友圈
                                shareToMoment();
                                break;
                            case 4: // 微博
                                shareToSina();
                                break;
                        }
                    }
                }
            });
        }


    }

    public ShareAppUtils(Context context, int shareFlag, Bitmap bitmap) {
        this.mContext = context;
        this.mShareFlag = shareFlag;
        this.shareBitmap = bitmap;
        switch (mShareFlag) {
            case 1: // qq
                shareImageToQQ();

                break;
            case 2: // 微信
                shareImageToWeiXin();
                break;
            case 3: // 朋友圈
                shareImageToMoment();
                break;
            case 4: // 微博
                shareToSina();
                break;
        }
    }

    /**
     * 分享到微信
     */
    private void shareToWeiXin() {
        api = WXAPIFactory.createWXAPI(mContext, Constants.WEIXIN_APP_ID, true);
        api.registerApp(Constants.WEIXIN_APP_ID);
        //
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = mShareUrl;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = mShareTitle;
        msg.description = mShareDesc;
        if (shareBitmap == null) {
            shareBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.logo);
        }
        msg.thumbData = Util.bmpToByteArray(shareBitmap, 30 * 1000);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
        shareBitmap = null;
    }

    /**
     * 分享到微信朋友圈
     */
    private void shareToMoment() {
        api = WXAPIFactory.createWXAPI(mContext, Constants.WEIXIN_APP_ID, true);
        api.registerApp(Constants.WEIXIN_APP_ID);
        //
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = mShareUrl;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = mShareTitle;
        msg.description = mShareDesc;
        if (shareBitmap == null) {
            shareBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.logo);
        }
        msg.thumbData = Util.bmpToByteArray(shareBitmap, 30 * 1000);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneTimeline;
        api.sendReq(req);
        shareBitmap = null;
    }

    //分享图片到微信
    public void shareImageToWeiXin() {
        api = WXAPIFactory.createWXAPI(mContext, Constants.WEIXIN_APP_ID, true);
        api.registerApp(Constants.WEIXIN_APP_ID);

        Bitmap bitmap = shareBitmap;
//        if (mShareImage.equals("1")) {
//            bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.jia_poster_1);
//        } else if (mShareImage.equals("2")) {
//            bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.jia_poster_2);
//        } else if (mShareImage.equals("3")) {
//            bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.jia_poster_3);
//        } else if (mShareImage.equals("4")) {
//            bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.jia_poster_4);
//        }

        //
        WXImageObject wxImageObject = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = wxImageObject;
        //
        Bitmap thumbBitmap = Bitmap.createScaledBitmap(bitmap, 60, 60, false);
        bitmap.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBitmap, false);
        //
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "img";
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    //分享图片到朋友圈
    public void shareImageToMoment() {
        api = WXAPIFactory.createWXAPI(mContext, Constants.WEIXIN_APP_ID, true);
        api.registerApp(Constants.WEIXIN_APP_ID);


        Bitmap bitmap = shareBitmap;
//        if (mShareImage.equals("1")) {
//            bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.jia_poster_1);
//        } else if (mShareImage.equals("2")) {
//            bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.jia_poster_2);
//        } else if (mShareImage.equals("3")) {
//            bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.jia_poster_3);
//        } else if (mShareImage.equals("4")) {
//            bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.jia_poster_4);
//        }
        //
        WXImageObject wxImageObject = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = wxImageObject;
        //
        Bitmap thumbBitmap = Bitmap.createScaledBitmap(bitmap, 60, 60, true);
        bitmap.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBitmap, false);
        //
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "img";
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneTimeline;
        api.sendReq(req);
    }


    /**
     * 分享到QQ
     */
    public void shareToQQ() {
        TENCENT = Tencent.createInstance(Constants.QQ_APP_ID, mContext.getApplicationContext());
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, mShareTitle);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, mShareDesc);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, mShareUrl);
        if (!TextUtils.isEmpty(mShareImage) && (mShareImage.startsWith("http") || mShareImage.startsWith("https"))) {
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, mShareImage);
        } else {
            String filepath = Utils.getPath(mContext) + File.separator + Constants.localThumbPath + File.separator + "sharepic.png";
            Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.logo);
            try {
                ImageUtils.saveImageToSD(mContext, filepath, bitmap, Bitmap.CompressFormat.PNG, 70);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, filepath);
        }
        // params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, mShareImage);
        // params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
        // "http://imgcache.qq.com/qzone/space_item/pre/0/66768.gif");
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, mContext.getResources().getString(com.youmbe.library.R.string.app_name));
        // params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, "其他附加功能");
//        TENCENT.shareToQQ(((Activity) mContext), params, new IUiListener() {
//            @Override
//            public void onError(UiError e) {
//                // TODO Auto-generated method stub
//                Global.showToast(e.errorMessage + "-" + e.errorCode, mContext);
//            }
//
//            @Override
//            public void onComplete(Object arg0) {
//                // TODO Auto-generated method stub
//                new Coco3gBroadcastUtils(mContext).sendBroadcast(Coco3gBroadcastUtils.SHARE_SUCCESS, null);
//            }
//
//            @Override
//            public void onCancel() {
//                // TODO Auto-generated method stub
//                Global.showToast("用户取消", mContext);
//            }
//        });
        TENCENT.shareToQQ(((Activity) mContext), params, qqShareListener);
    }

    /**
     * 分享到QQ
     */
    public void shareImageToQQ() {
        TENCENT = Tencent.createInstance(Constants.QQ_APP_ID, mContext.getApplicationContext());
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
        if (!TextUtils.isEmpty(mShareImage) && (mShareImage.startsWith("http") || mShareImage.startsWith("https"))) {
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, mShareImage);
        } else {
            String filepath = Utils.getPath(mContext) + File.separator + Constants.localThumbPath + File.separator + "sharepic.png";
//            Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
            Bitmap bitmap = shareBitmap;
            try {
                ImageUtils.saveImageToSD(mContext, filepath, bitmap, Bitmap.CompressFormat.PNG, 70);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, filepath);
        }
        // params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, mShareImage);
        // params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
        // "http://imgcache.qq.com/qzone/space_item/pre/0/66768.gif");
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, mContext.getResources().getString(com.youmbe.library.R.string.app_name));
        // params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, "其他附加功能");
//        TENCENT.shareToQQ(((Activity) mContext), params, new IUiListener() {
//            @Override
//            public void onError(UiError e) {
//                // TODO Auto-generated method stub
//                Global.showToast(e.errorMessage + "-" + e.errorCode, mContext);
//            }
//
//            @Override
//            public void onComplete(Object arg0) {
//                // TODO Auto-generated method stub
//                new Coco3gBroadcastUtils(mContext).sendBroadcast(Coco3gBroadcastUtils.SHARE_SUCCESS, null);
//            }
//
//            @Override
//            public void onCancel() {
//                // TODO Auto-generated method stub
//                Global.showToast("用户取消", mContext);
//            }
//        });
        TENCENT.shareToQQ(((Activity) mContext), params, qqShareListener);
    }

    public static IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
            MyToast.showToast("用户取消", mContext);
            ((Activity) mContext).finish();
        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
//            new Coco3gBroadcastUtils(mContext).sendBroadcast(Coco3gBroadcastUtils.SHARE_SUCCESS, null);

            EventBus.getDefault().post(new ShareMsg(ShareMsg.share_type_qq));
            ((Activity) mContext).finish();
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub
            MyToast.showToast(e.errorMessage + "-" + e.errorCode, mContext);
            ((Activity) mContext).finish();
        }
    };

    AuthInfo authInfo;
    /**
     * 分享到微博
     */
    private void shareToSina() {
//        authInfo = new AuthInfo(mContext, WEIBO_APP_KEY, WEIBO_REDIRECT_URL, WEIBO_SCOPE);
//        WbSdk.install(mContext, authInfo);
//
//        shareHandler = new WbShareHandler((Activity) mContext);
//        shareHandler.registerApp();
////        shareHandler.

        WebpageObject webpageObject = new WebpageObject();
        webpageObject.identify = Utility.generateGUID();
        webpageObject.title = mShareTitle;
        webpageObject.description = mShareDesc;
        webpageObject.actionUrl = mShareUrl;
        webpageObject.setThumbImage(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.logo));

        Intent intent = new Intent(mContext, ShareToWeiBoActivity.class);
        intent.putExtra("data", webpageObject);
        mContext.startActivity(intent);

//        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
//        shareHandler.shareMessage(weiboMessage, true);

        /////////////////上边为新sdk，下边为旧的sdk///////////////
//        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(mContext, Constants.WEIBO_APP_KEY);
//        mWeiboShareAPI.registerApp();
//        int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
//        // if (supportApiLevel >= 10351) {
//        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
//        weiboMessage.mediaObject = getWebpageObj();
//        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
//        // 用transaction唯一标识一个请求
//        request.transaction = String.valueOf(System.currentTimeMillis());
//        request.multiMessage = weiboMessage;
//        //
////        AuthInfo authInfo = new AuthInfo(mContext, Constants.WEIBO_APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE);
////        // Oauth2AccessToken accessToken =
////        // AccessTokenKeeper.readAccessToken(getApplicationContext());
////        Oauth2AccessToken accessToken = null;
////        String token = "";
////        if (accessToken != null) {
////            token = accessToken.getToken();
////        }
//        mWeiboShareAPI.sendRequest(((Activity) mContext), request);
////        mWeiboShareAPI.sendRequest(((Activity) mContext), request, authInfo, token, new WeiboAuthListener() {
////            @Override
////            public void onWeiboException(WeiboException e) {
////                e.printStackTrace();
////            }
////
////            @Override
////            public void onComplete(Bundle bundle) {
////                // TODO Auto-generated method stub
////                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
////                Global.showToast("onAuthorizeComplete token = " + newToken.getToken(), mContext);
////            }
////
////            @Override
////            public void onCancel() {
////                Global.showToast("用户取消", mContext);
////            }
////        });

    }


    public void onNewIntent(Intent intent) {
        shareHandler.doResultIntent(intent, new WbShareCallback() {
            @Override
            public void onWbShareSuccess() {

            }

            @Override
            public void onWbShareCancel() {

            }

            @Override
            public void onWbShareFail() {

            }
        });
    }

//    /**
//     * 创建多媒体（网页）消息对象。
//     *
//     * @return 多媒体（网页）消息对象。
//     */
//    private WebpageObject getWebpageObj() {
//        WebpageObject mediaObject = new WebpageObject();
//        mediaObject.identify = Utility.generateGUID();
//        mediaObject.title = mShareTitle;
//        if (TextUtils.isEmpty(mShareDesc)) {
//            mShareDesc = mContext.getString(R.string.app_name);
//        }
//        mediaObject.description = mShareDesc;
//        if (shareBitmap == null) {
//            shareBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
//        }
////        // 设置 Bitmap 类型的图片到视频对象里 设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
//        mediaObject.setThumbImage(shareBitmap);
//        mediaObject.actionUrl = mShareUrl;
//        mediaObject.defaultText = mShareDesc;
//        return mediaObject;
//    }
}
